# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '2047': {  # dwc 支付宝：3.5%（50---1w）do结算。
        'API_KEY': '77fcb20035716f861338332bf19fb341',
        'gateway': 'http://open.8wpay.com/online/gateway',
    },
    '2101': {  # ks 支付宝：3%（100---1w）d0结算。
        'API_KEY': '7fa58c361f6bd660e660dd4246e0a218',
        'gateway': 'http://open.8wpay.com/online/gateway',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


# version={0}&method={1}&partner={2}&banktype={3}&paymoney={4}&ordernumber={5}&callbackurl={6}key
def generate_sign(d, key):
    s = 'version={}&method={}&partner={}&banktype={}&paymoney={}&ordernumber={}&callbackurl={}{}'.format(
        d['version'], d['method'], d['partner'], d['banktype'], d['paymoney'], d['ordernumber'], d['callbackurl'], key
    )
    _LOGGER.info("yizhipay sign str: %s", s)
    return _gen_sign(s)


# partner={}&ordernumber={}&orderstatus={}&paymoney={}key
def generate_notify_sign(d, key):
    s = 'partner={}&ordernumber={}&orderstatus={}&paymoney={}{}'.format(
        d['partner'], d['ordernumber'], d['orderstatus'], d['paymoney'], key
    )
    _LOGGER.info("yizhipay generate_notify_sign str: %s", s)
    return _gen_sign(s)


def generate_query_sign(d, key):
    s = 'version={}&method={}&partner={}&ordernumber={}&sysnumber=&key={}'.format(
        d['version'], d['method'], d['partner'], d['ordernumber'], key
    )
    _LOGGER.info("yizhipay generate_query_sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("yizhipay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# ALIPAYWAP	WAP支付宝
# TENPAYWAP	WAP财付通
# WEIXINWAP	WAP微信
# QQWAP	WAPQQ钱包
# BAIDU	百度钱包
# BAIDUWAP	百度WAP钱包
# JDPAY	京东钱包
# JDWAP	京东WAP钱包
# SHORTCUT	快捷支付
# SHORTCUTWAP	WAP快捷支付
# UNIONPAY	银联钱包
# UNIONPAYWAP	银联WAP钱包
def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'WEIXINWAP'
    elif service == 'alipay':
        payType = 'ALIPAYWAP'
    elif service == 'qq':
        payType = 'QQWAP'
    elif service == 'quick':
        payType = 'SHORTCUTWAP'
    else:
        payType = 'JDWAP'
    return payType


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('version', '3.0'),
        ('method', 'yzfapp.online.interface'),
        ('partner', app_id),
        ('banktype', _get_pay_type(service)),
        ('paymoney', '%.2f' % pay_amount),
        ('ordernumber', str(pay.id)),
        ('callbackurl', '{}/pay/api/{}/yizhipay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    _LOGGER.info("yizhipay create: %s", html_text)
    cache_id = redis_cache.save_html(pay.id, html_text)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# ok
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("yizhipay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['ordernumber']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('yizhipay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['orderstatus'])
    trade_no = data['sysnumber']
    total_fee = float(data['paymoney'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 1:支付成功，非1为支付失败
    if trade_status == '1':
        _LOGGER.info('yizhipay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('version', '3.0'),
        ('method', 'yzfapp.online.query'),
        ('partner', app_id),
        ('ordernumber', str(pay_order.id)),
    ))
    parameter_dict['sign'] = generate_query_sign(parameter_dict, api_key)
    _LOGGER.info('yizhipay query data, %s', parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info('yizhipay query rsp, %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['tradestate'])
        total_fee = float(data['paymoney'])
        trade_no = data['sysnumber']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        # 订单状态, 0:支付中, 1:成功, 2:失败
        if trade_status == '1':
            _LOGGER.info('yizhipay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
